import { defineConfig, loadEnv } from 'vite'
import vue from '@vitejs/plugin-vue'
import { resolve } from 'path'
import {createVitePlugins} from "../yudao-ui-admin-vue3/build/vite";
// 当前执行node命令时文件夹的地址(工作目录)
const root = process.cwd()

// 路径查找
function pathResolve(dir: string) {
  return resolve(root, '.', dir)
}
// https://vitejs.dev/config/
export default defineConfig(({ command, mode }) => {
  // 加载环境变量
  const env = loadEnv(mode, process.cwd())
  const isBuild = command === 'build'

  return {
    // 基础路径
    base: '/screen/',
    root: root,
    // 插件配置
    // plugins: [vue()],
    plugins: createVitePlugins(),

    // 开发服务器配置
    server: {
      port: parseInt(env.VITE_PORT || '8080'),  // 从环境变量读取
      open: true,
      host: "0.0.0.0",
      // 代理配置
      proxy: {
        '/api': {
          target: 'http://localhost:3000',
          changeOrigin: true,
          rewrite: (path) => path.replace(/^\/api/, '')
        }
      }
    },

    // 构建配置
    build: {
      outDir: 'dist',
      assetsDir: 'static',
      sourcemap: false,
      // rollup 配置
      rollupOptions: {
        output: {
          chunkFileNames: 'static/js/[name]-[hash].js',
          entryFileNames: 'static/js/[name]-[hash].js',
          assetFileNames: (assetInfo) => {
            const info = assetInfo.name.split('.')
            const ext = info[info.length - 1]
            if (/\.(css|scss|sass)$/.test(assetInfo.name)) {
              return 'static/css/[name]-[hash].[ext]'
            }
            if (/\.(png|jpe?g|gif|svg|webp|ico)$/.test(assetInfo.name)) {
              return 'static/images/[name]-[hash].[ext]'
            }
            if (/\.(woff2?|eot|ttf|otf)$/.test(assetInfo.name)) {
              return 'static/fonts/[name]-[hash].[ext]'
            }
            return 'static/assets/[name]-[hash].[ext]'
          }
        }
      }
    },

    // CSS 预处理器配置
    css: {
      preprocessorOptions: {
        scss: {
          additionalData: `@use "@/styles/variables.scss" as *;`
        }
      }
    },

    // 路径解析
    resolve: {
      extensions: ['.mjs', '.js', '.ts', '.jsx', '.tsx', '.json', '.scss', '.css'],
      alias:
          {
            '@': resolve(__dirname, 'src'),
            'assets': resolve(__dirname, 'src/assets'),
            'components': resolve(__dirname, 'src/components'),
            'views': resolve(__dirname, 'src/views'),
            'utils': resolve(__dirname, 'src/utils')
          }
    },

    // 优化依赖
    optimizeDeps: {
      include: [] // 可以根据需要添加需要预构建的依赖
    }
  }
})